<script setup lang="ts">
import { useVbenForm, useVbenModal, type VbenFormProps } from '@vben/common-ui';
import { Page } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';

import { useVbenVxeGrid, type VxeGridProps } from '#/adapter/vxe-table';
import { addPayLog, getAllPayLog } from '#/api/core/topup';

const enums = {
  payTypes: [
    {
      label: '全部',
      value: '',
    },
    {
      label: '支付宝',
      value: 1,
      color: 'blue',
    },
    {
      label: '对公',
      value: 2,
      color: 'orange',
    },
    {
      label: '线下(手动)',
      value: 3,
      color: 'cyan',
    },
  ],
  logTypes: [
    {
      label: '全部',
      value: '',
    },
    {
      label: '充值',
      value: 0,
      color: 'green',
    },
    {
      label: '提现',
      value: 1,
      color: 'blue',
    },
  ],
};
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  commonConfig: {
    colon: true,
    // 所有表单项
  },
  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      label: '姓名',
    },
    {
      component: 'Select',
      componentProps: {
        options: enums.logTypes,
      },
      fieldName: 'logType',
      label: '交易类别',
    },
    {
      component: 'Select',
      componentProps: {
        options: enums.payTypes,
      },
      fieldName: 'payType',
      label: '交易方式',
    },
  ],
  // 是否可展开
  showCollapseButton: false,
  submitOnChange: true,
  submitOnEnter: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    {
      cellRender: { name: 'CellTag', options: enums.logTypes },
      field: 'logType',
      sortable: true,
      title: '交易类别',
    },
    { field: 'name', title: '姓名' },
    { field: 'payAccount', sortable: true, title: '支付宝账号' },
    { field: 'amount', sortable: true, title: '金额' },
    { field: 'userId', sortable: true, title: '用户Id' },
    {
      field: 'payType',
      sortable: true,
      title: '交易方式',
      cellRender: { name: 'CellTag', options: enums.payTypes },
    },
    // {
    // align: 'right',
    // cellRender: {
    //   attrs: {
    //     nameField: 'name',
    //     onClick: onActionClick,
    //   },
    //   name: 'CellOperation',
    //   options: [
    //     'edit', // 默认的编辑按钮
    //     // 'delete', // 默认的删除按钮
    //   ],
    // },
    // field: 'operation',
    // fixed: 'right',
    // headerAlign: 'center',
    // showOverflow: false,
    // title: '操作',
    // width: 100,
    // },
  ],
  editConfig: {
    mode: 'row',
    trigger: 'click',
  },
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    response: {
      result: 'list',
      total: 'total',
      list: 'list',
    },
    ajax: {
      query: async ({ page }) => {
        const res = await getAllPayLog({
          currentPage: page.currentPage,
          pageSize: page.pageSize,
          filter: {
            logType: 0,
            payNo: '',
            payAccount: '',
            doneStatus: 0,
          },
        });
        return res.data;
      },
    },
  },
  showOverflow: false,
};
const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
function onRefresh() {
  gridApi.query();
}

function onActionClick({ code, row }: { code: string; row: any }) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    default: {
      break;
    }
  }
}

function onDelete(row: any) {
  console.warn('删除', row);
  // deleteMenu(row.id)
  //   .then(() => {
  //     message.success({
  //       content: $t('ui.actionMessage.deleteSuccess', [row.name]),
  //       key: 'action_process_msg',
  //     });
  //     onRefresh();
  //   })
  //   .catch(() => {});
}

const [BaseForm, baseFormApi] = useVbenForm({
  // 默认展开
  collapsed: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    colon: true,
    // 所有表单项
    componentProps: {
      class: 'w-[80%]',
    },
  },
  showDefaultActions: false,
  // 提交函数
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      component: 'RadioGroup',
      componentProps: {
        options: enums.logTypes,
      },
      rules: 'required',
      fieldName: 'logType',
      label: '交易类别',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: enums.payTypes,
      },
      rules: 'required',
      fieldName: 'payType',
      label: '交易方式',
    },
    {
      component: 'Input',
      fieldName: 'name',
      label: '姓名',
    },
    {
      component: 'Input',
      fieldName: 'payAccount',
      label: '支付宝账号',
    },
    {
      component: 'InputNumber',
      componentProps: {
        min: 0,
      },
      fieldName: 'amount',
      suffix: () => '¥',
      label: '金额',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: Array.from({ length: 10 })
          .fill({})
          .map((_, index) => ({
            label: `用户${index + 1}`,
            value: index + 1,
          })),
      },
      fieldName: 'userId',
      label: '用户',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: enums.payTypes,
      },
      dependencies: {
        show(values) {
          return values.payType === 1;
        },
        triggerFields: ['payNo'],
      },
      fieldName: 'payType',
      label: '交易方式',
    },
    {
      component: 'Input',
      fieldName: 'payNo',
      label: '支付宝交易号',
    },
    {
      component: 'Textarea',
      componentProps: {
        autoSize: { minRows: 2, maxRows: 5 },
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],

  wrapperClass: 'grid-cols-1',
});

const [Modal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm() {
    modalApi.setState({
      confirmLoading: true,
    });
    baseFormApi
      .validateAndSubmitForm()
      .then((val) => {
        if (val) {
          addPayLog({
            ...val,
          }).then((res) => {
            if (res.success === true) {
              message.success('添加成功');
              modalApi.close();
              onRefresh();
            } else {
              message.error(res.msg);
            }
          });
        }
      })
      .finally(() => {
        modalApi.setState({
          confirmLoading: false,
        });
      });
  },
});

function onEdit(row: any) {
  baseFormApi.setValues({
    ...row,
  });
  modalApi.open();
}
function handleAdd() {
  modalApi.open();
}
</script>
<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <Button type="primary" @click="handleAdd"> 新增 </Button>
      </template>
      <template #logType="{ row }">
        <span>{{ row.logType === 0 ? '充值' : '提现' }}</span>
      </template>
    </Grid>
    <Modal class="w-[40vw]" title="新增交易记录">
      <BaseForm />
    </Modal>
  </Page>
</template>

<style lang="scss" scoped>
.page {
  background: white;
  padding: 20px;
}
</style>
<style>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
